import React  from 'react'
import { Badge } from 'antd'
import { Link } from 'react-router-dom'
import { createFromIconfontCN } from '@ant-design/icons'
import storage from '../../Utils/storage'
import $http from '../../Utils/request'
import { connect } from 'react-redux'
import { setCartNum } from '../../actions/cartAction'
//引入react图标标签
const IconFont = createFromIconfontCN({
  scriptUrl: [
    '//at.alicdn.com/t/font_1788044_0dwu4guekcwr.js',
    '//at.alicdn.com/t/font_1788592_a5xf2bdic3u.js', // icon-shoppingcart, icon-python
  ],
});
class ShoppingCartNum extends React.Component {

  constructor (props) {
    super(props);
    this.state ={
      cartNum : 0
    }
  }
  componentDidMount () {
    this.getShoppingCartNum();
  }

  getShoppingCartNum(){
    const { userTokenInfo } = this.props
    debugger
    console.log('token===>',storage.get("token"))
    console.log('userTokenInfo--->',userTokenInfo)

    const {dispatch} = this.props
    //创建请求头文件
    let config = {}
    if(storage.get("token") !== null){
      config = {
        headers:
          {'Content-Type': 'application/json',
            'token':storage.get("token").data
          }
      }
    }else{
      config = {
        headers:
          {'Content-Type': 'application/json'}
      }
    }
    //请求后台查询数据
    $http.get("http://localhost/mall-basic-service/basic/shoppingCart/queryShoppingCartToUserId",config).then((response)=>{
      if( response.data.code !== '500'){
        //查询该用户的购物车数量
        dispatch(setCartNum(response.data.data.length))
      }
    })
  }

  render () {
    const {carts} = this.props
    return (
      <div>
        <Link to={"/toShoppingCart"} >
          <Badge count={carts}>
            <IconFont type="icon-shoppingcart" style={{fontSize:20,color:"#337ab7"}}/>
          </Badge>
        </Link>
      </div>
    )
  }
}

const mapStateToProps = (state) =>{
  return {
    carts: state.get('cartNum'),
    userTokenInfo: state.get('userTokenInfo'),
  }
}
export default connect(mapStateToProps)(ShoppingCartNum)
